<template>
  <div class="event-addition-container">
    <div class="controls">
      <button
        @click="activateDraw('Point')"
        :class="{ active: drawType === 'Point' }"
      >
        绘制点
      </button>
      <button
        @click="activateDraw('LineString')"
        :class="{ active: drawType === 'LineString' }"
      >
        绘制线
      </button>
      <button
        @click="activateDraw('Polygon')"
        :class="{ active: drawType === 'Polygon' }"
      >
        绘制面
      </button>
      <button @click="clearDrawing" v-if="currentFeature">清除绘制</button>
    </div>

    <div v-if="showEventCard" class="event-card">
      <h4>添加事件信息</h4>
      <input type="text" v-model="eventDetails.name" placeholder="事件名称" />
      <textarea
        v-model="eventDetails.description"
        placeholder="事件描述"
      ></textarea>
      <select v-model="eventDetails.type">
        <option disabled value="">请选择事件类型</option>
        <option>交通事故</option>
        <option>道路施工</option>
        <option>拥堵</option>
        <option>其他</option>
      </select>
      <button @click="saveEvent">保存事件</button>
      <button @click="cancelEvent">取消</button>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onUnmounted, watch } from 'vue'
// 假设 OpenLayers (ol) 是全局引入的

const map = inject('mapInstance', ref(null))
const drawInteraction = ref(null)
const drawLayer = ref(null)
const currentFeature = ref(null)
const showEventCard = ref(false)
const drawType = ref('')

const eventDetails = ref({
  name: '',
  description: '',
  type: '',
  geometry: null,
})

const createDrawLayer = () => {
  if (!map.value) return null
  if (drawLayer.value) {
    map.value.removeLayer(drawLayer.value) // 移除旧的绘制图层
  }
  const source = new ol.source.Vector()
  const layer = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0.2)',
      }),
      stroke: new ol.style.Stroke({
        color: '#ffcc33',
        width: 2,
      }),
      image: new ol.style.Circle({
        radius: 7,
        fill: new ol.style.Fill({
          color: '#ffcc33',
        }),
      }),
    }),
    title: 'DrawLayer',
  })
  map.value.addLayer(layer)
  return layer
}

const activateDraw = (type) => {
  if (!map.value) {
    console.warn('地图实例未提供')
    return
  }
  if (drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value)
  }
  if (!drawLayer.value) {
    drawLayer.value = createDrawLayer()
  }

  drawType.value = type
  currentFeature.value = null // 清除上一个绘制的要素
  drawLayer.value.getSource().clear() // 清空图层上的要素
  showEventCard.value = false

  drawInteraction.value = new ol.interaction.Draw({
    source: drawLayer.value.getSource(),
    type: type,
  })

  drawInteraction.value.on('drawend', (event) => {
    currentFeature.value = event.feature
    eventDetails.value.geometry = event.feature.getGeometry().clone() // 保存几何信息
    showEventCard.value = true // 显示事件信息卡片
    map.value.removeInteraction(drawInteraction.value) // 绘制完成后移除交互，避免重复绘制
    drawInteraction.value = null
    drawType.value = '' // 重置绘制类型
  })

  map.value.addInteraction(drawInteraction.value)
}

const clearDrawing = () => {
  if (drawLayer.value && currentFeature.value) {
    drawLayer.value.getSource().removeFeature(currentFeature.value)
  }
  currentFeature.value = null
  showEventCard.value = false
  eventDetails.value = { name: '', description: '', type: '', geometry: null }
  if (drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value)
    drawInteraction.value = null
  }
  drawType.value = ''
}

const saveEvent = () => {
  if (
    !currentFeature.value ||
    !eventDetails.value.name ||
    !eventDetails.value.type
  ) {
    alert('请完成绘制并填写事件名称和类型')
    return
  }
  // 在这里处理保存事件的逻辑，例如发送到后端API
  console.log('保存事件:', {
    ...eventDetails.value,
    // 可以将 geometry 转换为 GeoJSON 格式
    geometryGeoJSON: new ol.format.GeoJSON().writeFeatureObject(
      currentFeature.value
    ),
  })
  alert('事件已保存！')
  // 清理
  clearDrawing()
  // 可以在这里将保存的事件要素添加到永久图层
}

const cancelEvent = () => {
  clearDrawing()
}

// 当组件卸载时，移除交互和图层
onUnmounted(() => {
  if (map.value && drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value)
  }
  if (map.value && drawLayer.value) {
    map.value.removeLayer(drawLayer.value)
  }
})

// 监听地图实例的变化，确保在地图加载后再尝试创建图层
watch(
  () => map.value,
  (newMap) => {
    if (newMap && !drawLayer.value) {
      // 如果之前因为 map 未加载而未创建图层，可以考虑在这里初始化
      // 但通常绘制操作由用户触发，所以可能不需要自动创建
    }
  }
)
</script>

<style scoped lang="scss">
.event-addition-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 控制按钮和卡片左对齐 */
  padding: 5px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 0 5px;
}

.controls {
  display: flex;
  gap: 5px;
  margin-bottom: 10px;
  button {
    padding: 6px 10px;
    background-color: #f0ad4e; /* 橙色，表示操作/编辑 */
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    &.active {
      background-color: #ec971f; /* 更深的橙色表示激活状态 */
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
    }
    &:hover {
      background-color: #eea236;
    }
  }
}

.event-card {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  width: 280px; /* 固定卡片宽度 */
  display: flex;
  flex-direction: column;
  gap: 10px;

  h4 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 14px;
    color: #333;
  }

  input[type='text'],
  textarea,
  select {
    width: calc(100% - 16px); /* 减去padding */
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 3px;
    font-size: 12px;
  }

  textarea {
    min-height: 60px;
    resize: vertical;
  }

  button {
    padding: 8px 12px;
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    &:first-of-type {
      background-color: #5cb85c; /* 保存按钮 - 绿色 */
      &:hover {
        background-color: #4cae4c;
      }
    }
    &:last-of-type {
      background-color: #d9534f; /* 取消按钮 - 红色 */
      &:hover {
        background-color: #c9302c;
      }
    }
  }
}
</style>
